#coding:utf-8
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.forms.models import modelformset_factory
from django.db.models import Sum, Count
from django.http import HttpResponse,HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth, messages
from django.db import transaction
from models import *
from forms import *
from utils import *
from urllib import urlencode
from django.views.decorators.csrf import csrf_protect
from django.template.context import RequestContext
import Image,hashlib,os
from settings import UPLOAD_ROOT,MEDIA_ROOT

@never_cache
def index(request):
    header = 'all'
    devices = Device.objects.filter(audit=1).order_by('-last_update')[0:30]  
    
    tags = Tag.objects.all()
    topics = Topic.objects.hot_topics()
    return render_to_response('device.html', locals())

def device_os(request,head):
    header = head or 'all'
    try:
        if header == "all" :
            devices = Device.objects.order_by('-last_update')[0:30]   
        else:
            devices = Tag.objects.get(name=header).dev_tags.all()[0:30]
    except:
        devices = [] #
    topics = Topic.objects.hot_topics()                                                                                                                             
    return render_to_response('device.html', locals())    
    

@never_cache
def detail(request,devid):
    device = Device.objects.get(pk=devid)
    
    stat = DeviceStar.objects.filter(device=device).aggregate(Sum('value'), Count('value'),)
    if stat['value__count'] >0:
        import decimal
        stat_count = stat.get('value__count') or 0
        score_f = round(float(stat.get('value__sum')or 0)/stat_count or 0,1)
        score_val  = decimal.Decimal(str(score_f)) or 0

    print device.name
    tags = device.tags.all()
    comments = device.comments.extra(
        select={
            'user_image':'select image from  mobeir_userprofile where mobeir_comment.user_id = mobeir_userprofile.user_id',    
        }
    ).order_by("-last_update").select_related('user')
    
    features = DeviceFeature.objects.filter(device=device).select_related('user')[0:10]
    
  

    
    dev_photos = device.photos.all()
    dev_photo_count= device.photos.count()
    try:
        topics = Topic.objects.select_related().filter(group=device.group).order_by('-last_update')[0:15]
    except:
        topics = []
    debug_sql('device.detail')
    return render_to_response('device_one.html', locals())
    
@csrf_protect 
@never_cache
@transaction.commit_on_success
def star(request):
    
    if not request.user.is_authenticated():
        return HttpResponse(u"need login", mimetype="text/plain")
    if request.method =="POST":
        devid = request.POST.get('devid')
        star_value = request.POST.get('star')
        
        
        if not devid or not star_value:
            return HttpResponse("0", mimetype="text/plain")
        
        dev = Device.objects.get(id=devid)

        star = DeviceStar()
        star.user = request.user
        star.value = star_value
        star.device = dev
        star.save()
   
        stat = DeviceStar.objects.filter(device=dev).aggregate(Sum('value'), Count('value'),)
                         
        import decimal
        score_f = round(float(stat['value__sum'])/stat['value__count'],1)
        dev.score  = decimal.Decimal(str(score_f))
        dev.save()

        return HttpResponse(str(dev.score), mimetype="text/plain")
    
@csrf_protect 
@never_cache    
@transaction.commit_on_success    
def add_device(request):
    if not request.user.is_staff:
        return Http404
    
    if request.method == "POST":      
        form = DeviceForm(request.POST,request.FILES) 
        print  form
        if form.is_valid(): 
            try:
                device = form.save(commit=False)
                cd = form.cleaned_data
                apptags = cd.get('fmtags','').split(',') or []
                pretags = cd.get('pretags',[])
                devtags.extend(pretags)
                devtags.append('device')
                tags = []
                for dtag in devtags:
                    try:
                        tag = Tag.objects.get(name=dtag)
                        tags.append(tag)
                    except:
                        tag = Tag.objects.create(name=dtag)
                        tags.append(tag)                

                device.audit = True
                device.creater = request.user
                device.save() 
                for t in tags:
                    device.tags.add(t)                   
                form.save_m2m()


                title = u"新机型已经提交,请耐心等待审核通过"
                message = title
                backurl = "/device/"
                return render_to_response("redirect.html",locals())                
                
            except:
                import traceback
                traceback.print_exc()
                
                error = u"提交机型失败"
                return render_to_response('error.html', locals())     
        else:
            return render_to_response('add_device.html', locals()) 
            
            
    elif request.method == 'GET':
        form = DeviceForm()    
        return render_to_response('add_device.html', locals()) 
    
    
@csrf_protect 
@never_cache
@transaction.commit_on_success
def add_feature(request,devid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/device/feature/add/%s/'%devid}))     
    if request.method == "GET":
        try:
            device = Device.objects.get(id=devid)
        except:
            error = "没有找到这个手机"
            return render_to_response('error.html', locals()) 
        return render_to_response('add_device_feature.html', locals())   
    elif request.method == "POST":
        devid = request.POST.get('devid')
        device = Device.objects.get(id=devid)
        content = request.POST.get('content')
        ln = len(content)
        if ln ==0:
            messages.error(request,u"内容不能为空 ")
            return render_to_response('add_device_feature.html', locals(),context_instance=RequestContext(request))   
        
        if ln > 1024:
            messages.error(request,u"内容长度最多500个汉字 ")
            return render_to_response('add_device_feature.html', locals(),context_instance=RequestContext(request))             
            
        try:
            feature = DeviceFeature()
            feature.user = request.user
            feature.content = (content)
            feature.device = device
            feature.save()
            return HttpResponseRedirect("/device/detail/%s/"%devid)
        except:
            import traceback
            traceback.print_exc()
            error = "内容添加失败了，请稍后再试"
            return render_to_response('error.html', locals()) 
    
@csrf_protect  
@never_cache
@transaction.commit_on_success
def add_comment(request,devid):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/device/comment/add/%s/'%devid}))     
    if request.method == "GET":
        try:
            device = Device.objects.get(id=devid)
        except:
            error = "没有找到这个手机"
            return render_to_response('error.html', locals()) 
        return render_to_response('add_device_comment.html', locals())   
    elif request.method == "POST":
        devid = request.POST.get('devid')
        device = Device.objects.get(id=devid)
        star_val = request.POST.get('star_val') or 3
        content = request.POST.get('content')
        ln = len(content)
        if ln ==0:
            messages.error(request,u"内容不能为空 ")
            return render_to_response('add_device_comment.html', locals(),context_instance=RequestContext(request))            
        
        if ln > 1024:
            messages.error(request,u"内容长度最多500个汉字 ")
            return render_to_response('add_device_comment.html', locals(),context_instance=RequestContext(request))             
            
        try:
            comment = Comment()
            comment.user = request.user
            comment.star = int(star_val)
            comment.content = (content)
            comment.save()
            device.comments.add(comment)
            device.save()
            return HttpResponseRedirect("/device/detail/%s/"%devid)
        except:
            import traceback
            traceback.print_exc()
            error = "评论添加失败了，请稍后再试"
            return render_to_response('error.html', locals()) 
    
        
    
    
